from django.shortcuts import render, redirect
from app01 import models
from app01.form import RegForm, ArticleForm, ArticleDetailForm
import hashlib


# Create your views here.
def login(request):
    """
    登录页
    :param request:
    :return:
    """
    # 获取post请求
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        md5 = hashlib.md5()
        md5.update(password.encode('utf-8'))
        user_obj = models.User.objects.filter(user_name=username, pass_word=md5.hexdigest(),
                                              is_active=True).first()  # 查出来是对象，查不出来是null
        if user_obj:
            # 登录成功
            # 保存登录状态，用户名
            request.session['is_login'] = True
            request.session['username'] = user_obj.user_name
            url = request.GET.get('url')
            if url:
                return redirect(url)
            return redirect('index')  # 进入首页
        else:
            error = '用户名和密码错误'

    return render(request, 'login.html', locals())


def logout(request):
    """
    注销页面
    :param request:
    :return:
    """
    request.session.delete()
    return redirect('index')


def register(request):
    """
    注册页面
    :param request:
    :return:
    """
    form_obj = RegForm()
    if request.method == 'POST':
        form_obj = RegForm(request.POST, request.FILES)  # 将post数据重新实例化

        # 校验
        if form_obj.is_valid():
            # 注册成功
            # 将数据添加到数据库
            # print(form_obj.cleaned_data)  # 以字典的格式输出form表单中的数据
            # form_obj.cleaned_data.pop('re_pwd')  # 将与数据库无关的re_pwd字段删除掉
            # models.User.objects.create(**form_obj.cleaned_data)  # 将字典传入,可直接批量存入数据库
            form_obj.save()
            return redirect('login')
    return render(request, 'register.html', {'form_obj': form_obj})


def index(request):
    """
    主页
    :param request:
    :return:
    """
    # 查询所有文章
    all_article = models.Article.objects.all()
    # is_login = request.session.get('is_login')  # 拿到session中的登录状态
    # username = request.session.get('username')  # 拿到session中的用户名
    return render(request, 'index.html', {'all_article': all_article})


def article(request, pk):
    """
    文章详情
    :param request:
    :param pk:
    :return:
    """
    article_obj = models.Article.objects.get(pk=pk)
    return render(request, 'article.html', {'article_obj': article_obj})


def backend(request):
    """
    后台管理页面
    :param request:
    :return:
    """
    return redirect('article_list')
    # return render(request, 'dashboard.html')


def article_list(request):
    """
    后台文章列表
    :param request:
    :return:
    """
    all_article = models.Article.objects.all()
    return render(request, 'article_list.html', {'all_article': all_article})


# def article_add(request):
#     print(request)
#     obj = models.Article()
#     form_obj = ArticleForm(instance=obj)
#     article_detail_form_obj = ArticleDetailForm(instance=obj)
#     if request.method == 'POST':
#         form_obj = ArticleForm(request.POST, instance=obj)  # 创建对象，并接收
#         article_detail_form_obj = ArticleDetailForm(request.POST)
#         if form_obj.is_valid() and article_detail_form_obj.is_valid():  # 校验数据
#
#             detail_obj = article_detail_form_obj.save()  # 保存创建文章的对象
#             form_obj.instance.detail_id = detail_obj.pk  # instance是取对象的意思
#             form_obj.save()
#             return redirect('article_list')  # 重定向到列表页面
#     return render(request, 'article_add.html',
#                   {'form_obj': form_obj, 'article_detail_form_obj': article_detail_form_obj})

def article_add(request):
    form_obj = ArticleForm()
    if request.method == 'POST':
        form_obj = ArticleForm(request.POST)  # 创建对象，并接收
        if form_obj.is_valid():  # 校验数据
            print(form_obj.cleaned_data)
            form_obj.instance.detail_id = form_obj.cleaned_data['detail_id']  # instance是取对象的意思
            form_obj.instance.save()
            return redirect('article_list')  # 重定向到列表页面
    return render(request, 'article_add.html', {'form_obj': form_obj})


# 编辑文章
def article_edit(request, pk):
    obj = models.Article.objects.filter(pk=pk).first()
    form_obj = ArticleForm(instance=obj)  # (数据赋值)将实例对象传入其中，这样文章的所有数据都会出现在模板中
    if request.method == 'POST':
        form_obj = ArticleForm(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.instance.detail.content = request.POST.get('detail')  # 更新数据
            form_obj.save()  # 保存
            return redirect('article_list')
    return render(request, 'article_edit.html',
                  {'form_obj': form_obj, 'obj': obj})
